package com.mego.weblink.database.manager;


import android.database.SQLException;
import android.database.sqlite.SQLiteException;

import com.mego.weblink.activitys.AppContext;
import com.mego.weblink.database.dbmodel.Commandlog;
import com.mego.weblink.database.dbmodel.Lonlatlog;
import com.mego.weblink.database.greendao.CommandlogDao;
import com.mego.weblink.database.greendao.LonlatlogDao;
import com.mego.weblink.utils.GPSProvider;
import com.mego.weblink.utils.LonLat;
import com.mego.weblink.utils.Utils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class CommandlogCenter {

    private static CommandlogCenter instance = new CommandlogCenter();

    public static CommandlogCenter getInstance() {
        return instance;
    }


    private ArrayList<Commandlog> commandlogList = new ArrayList<Commandlog>();

    public ArrayList<Commandlog> getCommandlogList() {
        return commandlogList;
    }

    boolean _isClearHis = false;//开机后清理一次记录

    public void doQueryAll() {
        CommandlogDao commandlogDao = AppContext.getInstances().getDaoSession().getCommandlogDao();

        long thisday = System.currentTimeMillis();
        thisday -= 86400000 * 30L; // 没有L 会溢出

        if (!_isClearHis) {
            //删除30天前的数据
            _isClearHis = true;
            try {
                String deletesql = "DELETE FROM COMMANDLOG WHERE LOGTIME < " + thisday;
                commandlogDao.getDatabase().execSQL(deletesql);
            } catch (SQLException e) {
                return;
            }
        }

        try {
            commandlogList = (ArrayList) commandlogDao.queryBuilder()
                    .where(CommandlogDao.Properties.Logtime.ge(thisday))
                    .orderDesc(CommandlogDao.Properties.Id)
                    .build().list();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Long saveCommandlog(Commandlog commandlog) {
        if (commandlog == null) {
            return 0L;
        }

        long id = 0;
        try {
            CommandlogDao commandlogDao = AppContext.getInstances().getDaoSession().getCommandlogDao();
            id = commandlogDao.insertOrReplace(commandlog);
            commandlog.setId(id);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        return id;
    }

    public String saveCommandlog(String clog, String mobile) {
        if (clog == null || clog.length() < 3)
            return "";
        String[] cc = clog.split(",");

        if (clog.indexOf("$G01") != -1) {
            saveCommandlog(new Commandlog("1次回传", clog));
            if (cc.length == 2) {
                int s = Integer.valueOf(cc[1]);
                _jiage = 1000 * s;
                return getSendmsg1(mobile);
            }
        } else if (clog.indexOf("$G98") != -1) {
            //$G98,30
            saveCommandlog(new Commandlog("10次回传", clog));
            if (cc.length == 2) {
                int s = Integer.valueOf(cc[1]);
                _jiage10 = 1000 * s;
                _last10time = 0;
                _djnum = 10;
                _djmax = 10;
            }
        } else if (clog.indexOf("$G99") != -1) {
            if (cc.length == 5) {
                int s = Integer.valueOf(cc[2]);
                _Qnum = 0;
                _jiageQ = 1000 * s;
                _sendQtime = Utils.getDateTime(cc[3] + "," + cc[4], new SimpleDateFormat("HHmmss,ddMMyy"));//180000,030719
                _startQtime = System.currentTimeMillis();
                _sendQtime += 3600000L * 8;//UTC时间 + 8小时
            }

            String title = "全数回传";
            if (clog.compareToIgnoreCase("$G99,12,0,0") == 0) {
                title = "立即全数上传";
                _sendQtime = 0;
                return getSendmsg3(mobile);
            } else if (clog.compareToIgnoreCase("$G99,11,0,0") == 0) {
                title = "取消轨迹记录";
                _startQtime = 0;
                _sendQtime = 0;
                return getSendmsg3(mobile);
            }
            saveCommandlog(new Commandlog(title, clog));

            clearLonlatlog();//清空原记录
            //$G99,10,30,180000,030719
            //$G99,12,0,0  立即全数上传
            //$G99,11,0,0  取消轨迹记录

        } else if (clog.indexOf("$GON") != -1) {
            saveCommandlog(new Commandlog("RTC开机", clog));
            //$GON,180000,140619
            if (cc.length == 3) {
                _restarttime = Utils.getDateTime(cc[1] + "," + cc[2], new SimpleDateFormat("HHmmss,ddMMyy"));
                _restarttime += 3600000L * 8;//UTC时间 + 8小时
                _gjtime = System.currentTimeMillis() + 120 * 1000L;//120秒后关机
                _jiage = 1000 * 10; //心跳间隔变为10秒
            }

        } else if (clog.indexOf("$G97") != -1) {
            saveCommandlog(new Commandlog("心跳包间隔", clog));
            //$G97，30
            if (cc.length == 2) {
                int s = Integer.valueOf(cc[1]);
                _jiage = 1000 * s;
            }
        } else if (clog.indexOf("$GOF") != -1) {
            //取消关机
            _jiage = 1000 * 30;
            _gjtime = 0L;
            _restarttime = 0L;

        } else if (clog.indexOf("$G") != -1) {
            //$G20,30
            saveCommandlog(new Commandlog("指定次数回传", clog));

            if (cc.length == 2) {
                int m = Integer.valueOf(cc[0].replace("$G", ""));
                int s = Integer.valueOf(cc[1]);
                _jiage10 = 1000 * s;
                _last10time = 0;
                _djnum = m;
                _djmax = m;
            }
        }

        return "";
    }

    //发送心跳包
    long _lastXTtime = 0; //上次心跳发送时间
    long _jiage = 1000 * 30;//心跳间隔，默认30秒

    public String getSendmsg0(String mobile) {
        String msg = "";

        if (mobile.length() < 11) {
            return msg;
        }

        long thistime = System.currentTimeMillis();
        if (thistime < _lastXTtime + _jiage) {
            return msg;
        }
        _lastXTtime = thistime;

        thistime = thistime - 3600 * 8;

        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        Date curDate = new Date(thistime);
        String strDate = formatter.format(curDate);
        String strLL = getLLstr();

        // >06819296101,00,000106,A,000000.0000,00000.0000,1*
        msg = ">" + mobile + ",00," + strDate + ",A," + strLL + ",7*83";

        return msg;
    }

    //1次回传
    public String getSendmsg1(String mobile) {
        String msg = "";

        if (mobile.length() < 11) {
            return msg;
        }

        long thistime = System.currentTimeMillis() - 3600 * 8;

        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        Date curDate = new Date(thistime);
        String strDate = formatter.format(curDate);
        String strLL = getLLstr();

        SimpleDateFormat formatter2 = new SimpleDateFormat("ddMMyy");
        String strDate2 = formatter2.format(curDate);

        //>12345678911,00,082147,A,N2444.9859,E12144.4109,0.26,0.00,291018,0417,7*73
        msg = ">" + mobile + ",00," + strDate + ",A," + strLL + ",0.26,0.00," + strDate2 + ",0417,7*73";

        return msg;
    }

    //10次回传
    long _last10time = 0; //上次10次回传发送时间
    long _jiage10 = 1000 * 30;//10次回传间隔，默认30秒
    long _djnum = 10;//回传倒计数，10开始
    long _djmax = 10;//回传倒计总数 2～96

    public String getSendmsg2(String mobile) {
        String msg = "";

        if (mobile.length() < 11 || _djnum == 0) {
            return msg;
        }

        long thistime = System.currentTimeMillis();
        if (thistime < _last10time + _jiage10) {
            return msg;
        }
        _last10time = thistime;
        _djnum--;

        thistime = thistime - 3600 * 8;

        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        Date curDate = new Date(thistime);
        String strDate = formatter.format(curDate);
        String strLL = getLLstr();

        //"yyyy:MM:dd HH:mm:ss"
        SimpleDateFormat formatter2 = new SimpleDateFormat("ddMMyy");
        String strDate2 = formatter2.format(curDate);

        String strIndex = new DecimalFormat("00").format(_djmax - _djnum);
        //>12345678911,00,082147,A,N2444.9859,E12144.4109,0.26,0.00,291018,0417,7*73
        msg = ">" + mobile + "," + strIndex + "," + strDate + ",A," + strLL + ",0.26,0.00," + strDate2 + ",0417,7*73";

        return msg;
    }

    //全数上传
    long _sendQtime = 0; //全数上传发送时间
    long _startQtime = 0; //全数上传开始记录时间  如果为0，则没有全数上传的任务。
    long _jiageQ = 1000 * 30;//全数上传间隔，默认30秒
    int _Qnum = 0; //全数保存计数

    public String getSendmsg3(String mobile) {
        String msg = "";

        if (mobile.length() < 11 || _startQtime == 0) {
            return msg;
        }

        long thistime = System.currentTimeMillis();
        if (thistime < _sendQtime) {
            return msg;
        }
        _startQtime = 0;

        thistime = thistime - 3600 * 8;

        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        Date curDate = new Date(thistime);
        String strDate = formatter.format(curDate);

        ArrayList<Lonlatlog> lonlatlogList = doQueryLonlatlog();
        int size = lonlatlogList.size();
        if (size < 1) {
            return msg;
        }

        msg = ">" + mobile + ",99," + size + "," + strDate + ",A,";
        for (int i = 0; i < size; i++) {
            msg += lonlatlogList.get(i).getLonlatStr() + ",";
        }
        msg += "7*83";

        //>06819296188,99,00000207,132956,V,134106,000000.0000,00000.0000,134116,000000.0000,00000.0000,7*73
//        msg = ">" + mobile + "," + strIndex + "," + strDate + ",A," + strLL + ",0.26,0.00," + strDate2 + ",0417,7*73";

        return msg;
    }

    //定时开机
    long _restarttime = 0L; //定时开机时间
    long _gjtime = 0L;//

    public boolean needGj() {
        if (_gjtime == 0L) {
            return false;
        }

        long thistime = System.currentTimeMillis();
        if (thistime > _gjtime) {
            return true;
        }

        return false;
    }
    public boolean needKj() {
        if (_restarttime == 0L) {
            return false;
        }

        long thistime = System.currentTimeMillis();
        if (thistime > _restarttime) {
            _jiage = 1000 * 30;
            _gjtime = 0L;
            _restarttime = 0L;
            return true;
        }

        return false;
    }


    private String getLLstr() {

        String strLat = "000000.0000";
        String strLon = "000000.0000";

        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos.IsValid()) {
            double lat = pos.GetLat();
            double lon = pos.GetLon();

            String preLat = "N";
            if (lat < 0) {
                lat = -lat;
                preLat = "S";
            }
            int lat0 = (int) lat;
            double lat1 = (lat - lat0) * 60;
            strLat = preLat + new DecimalFormat("00.0000").format(lat0 * 100 + lat1);

            String preLon = "E";
            if (lon < 0) {
                lon = -lon;
                preLon = "W";
            }

            int lon0 = (int) lon;
            double lon1 = (lon - lon0) * 60;
            strLon = preLon + new DecimalFormat("00.0000").format(lon0 * 100 + lon1);

        }

        return strLat + "," + strLon;
    }

    public ArrayList<Lonlatlog> doQueryLonlatlog() {
        ArrayList<Lonlatlog> lonlatlogList = new ArrayList<Lonlatlog>();

        LonlatlogDao lonlatlogDao = AppContext.getInstances().getDaoSession().getLonlatlogDao();
        try {
            lonlatlogList = (ArrayList) lonlatlogDao.queryBuilder().build().list();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (lonlatlogList.size() < 1) {
            LonLat pos = GPSProvider.getInstance().getPos();
            lonlatlogList.add(new Lonlatlog(pos.GetLon(), pos.GetLat()));
        }
        return lonlatlogList;
    }

    public void clearLonlatlog() {
        try {
            LonlatlogDao lonlatlogDao = AppContext.getInstances().getDaoSession().getLonlatlogDao();
            lonlatlogDao.deleteAll();
        } catch (SQLException e) {

        }
        _Qnum = 0;
    }

    public void saveLonlatlogOne() {
        if (_startQtime == 0) {
            return;
        }
        long thistime = System.currentTimeMillis();

        if (thistime < _startQtime + _Qnum * _jiageQ * 1L) {
            return;
        }

        try {
            LonlatlogDao lonlatlogDao = AppContext.getInstances().getDaoSession().getLonlatlogDao();
            LonLat pos = GPSProvider.getInstance().getPos();
            lonlatlogDao.insert(new Lonlatlog(pos.GetLon(), pos.GetLat()));
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        _Qnum++;

    }

    public void addDemodata() {
        saveCommandlog(new Commandlog("一次回传", " $G01"));
        saveCommandlog(new Commandlog("10次回传", " $G98,30"));
        saveCommandlog(new Commandlog("指定次数回传", "$G20,60"));
        saveCommandlog(new Commandlog("全数回传", " $G99,10,30,180000,140619"));
        saveCommandlog(new Commandlog("RTC开机", " $GON,180000,140619"));
    }

}
